package com.viewpager2.teach;

import android.os.Bundle;
import android.os.Handler;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.MarginPageTransformer;
import androidx.viewpager2.widget.ViewPager2;

import com.google.android.material.tabs.TabLayout;
import com.viewpager2.teach.adapter.ViewPager2OneAdapter;
import com.viewpager2.teach.adapter.ViewPager2TwoAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * Creator:Yx
 * Time:2020/8/5 10:18
 * Description:ViewPager+Fragment
 */
public class TextTwoActivity extends AppCompatActivity {
    private ViewPager2 viewpager2;
    private List<Fragment> fragmentList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_text_two);
        initViewPager2();
    }

    private void initViewPager2() {
        viewpager2 = findViewById(R.id.public_viewPager2);
        //默认是水平方向ORIENTATION_HORIZONTAL,垂直是ORIENTATION_VERTICAL
        viewpager2.setOrientation(ViewPager2.ORIENTATION_HORIZONTAL);
        //设置页与页的间距
        viewpager2.setPageTransformer(new MarginPageTransformer(15));
        //设置翻页动画
        //CompositePageTransformer transformer = new CompositePageTransformer();
        //设置Adapter
        ViewPager2TwoAdapter adapter = new ViewPager2TwoAdapter(this);
        viewpager2.setAdapter(adapter);
        //设置预加载页数
        viewpager2.setOffscreenPageLimit(1);
        //设置是否允许用户输入/触摸。false用户就禁止手滑不了页。
        viewpager2.setUserInputEnabled(true);
        //设置翻页监听
        viewpager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels);
            }

            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                super.onPageScrollStateChanged(state);
            }
        });
        //模拟延迟数据设置
        new Handler().postDelayed(() -> {
            fragmentList.add(TextFragment.getInstance("页面一"));
            fragmentList.add(TextFragment.getInstance("页面二"));
            fragmentList.add(TextFragment.getInstance("页面三"));
            fragmentList.add(TextFragment.getInstance("页面四"));
            adapter.setFragmentData(fragmentList);
        }, 1000);

    }

}
